<script setup lang="ts">
import { getConsultOrderPre, patientConsultOrder, patientConsultPay } from '@/services/consult'
import { useConsultStore } from '@/stores'
import type { ConsultOrderPreData } from '@/types/consult'
import { onMounted, ref } from 'vue'
import { getPatientDetail } from '@/services/user'
import type { Patient } from '@/types/user'
import { showToast } from 'vant/lib/toast'
import { useRouter, onBeforeRouteLeave } from 'vue-router'
import { showConfirmDialog, showDialog } from 'vant'
const router = useRouter()
// -- 得到就诊信息&支付参数
// 得到 store 对象
const store = useConsultStore()
// 定义就诊信息对象
const payInfo = ref<ConsultOrderPreData>()
const patientObj = ref<Patient>()

async function loadData() {
  const res = await getConsultOrderPre({ type: store.consult.type, illnessType: store.consult.illnessType })
  payInfo.value = res.data
  console.log(store.consult.patientId)
  const patientRes = await getPatientDetail(store.consult.patientId!)
  console.log(patientRes)

  patientObj.value = patientRes.data
}
// 打开页面获取信息
onMounted(() => {
  // 判断问诊信息
  const { illnessDesc, illnessTime, consultFlag } = store.consult
  if (!illnessDesc || illnessTime === undefined || consultFlag === undefined) {
    // 提示不存在信息，跳转到首页
    showDialog({
      title: '温馨提示',
      message: '问诊信息不完整请重新填写，如有未支付的问诊订单可在问诊记录中继续支付',
      closeOnPopstate: false
    }).then(() => {
      // 跳转回首页
      router.push('/home')
    })
  }
  loadData()
})
const agree = ref<boolean>(false)
// 订单 id
const orderId = ref('')
async function submit() {
  // 请先同意协议
  if (!agree.value) return showToast('请签订不平等条约')
  // 生成订单
  const res = await patientConsultOrder(store.consult)
  console.log(res)
  orderId.value = res.data.id
  // 打开面板
  show.value = true
  // 清除之前的问诊信息
  store.clear()
}
const show = ref(false)
// 设置一个支付方式 支付方式0微信支付，1支付宝2云闪付
const paymentMethod = ref<0 | 1>()
// 请求支付接口页
async function pay() {
  const res = await patientConsultPay({
    paymentMethod: paymentMethod.value + '',
    orderId: orderId.value,
    payCallback: 'http://localhost:5173/room' // 支付成功后返回的页面路径
  })
  // 跳转到页面
  window.location.href = res.data.payUrl
}
function beforeClose() {
  // 提示
  showConfirmDialog({
    title: '关闭支付',
    message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭',
    cancelButtonText: '仍要关闭',
    confirmButtonText: '继续支付'
  })
    .then(() => {
      return false // 不关闭弹框继续支付
    })
    .catch(() => {
      // 跳转到首页
      // 清除订单 id,因为id不为空的话回退会被阻止
      orderId.value = ''
      router.push('/home')
    })
}
// 阻止回退
onBeforeRouteLeave(() => {
  if (orderId.value) return false
})
</script>

<template>
  <div class="consult-pay-page">
    <cp-nav-bar title="支付" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo?.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <h2>{{ payInfo?.couponDeduction }}</h2>
      <van-cell title="优惠券" :value="`-¥${payInfo?.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo?.pointDeduction}`" />
      <van-cell title="实付款" :value="`¥${payInfo?.actualPayment}`" class="pay-price" />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell title="患者信息" :value="`${patientObj?.name} | ${patientObj?.genderValue} | ${patientObj?.age}岁`"></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>
    <van-submit-bar @click="submit" button-type="primary" :price="payInfo?.actualPayment ? payInfo?.actualPayment * 100 : 0" button-text="立即支付" text-align="left" />
    <!-- 支付抽屉组件 -->
    <van-action-sheet v-model:show="show" title="选择支付方式" :closeable="false" :close-on-popstate="false" :before-close="beforeClose">
      <div class="pay-type">
        <p class="amount">￥{{ payInfo?.actualPayment.toFixed(2) }}</p>
        <van-cell-group>
          <van-cell title="微信支付" @click="paymentMethod = 0">
            <template #icon><cp-icon name="consult-wechat" /></template>
            <template #extra><van-checkbox :checked="paymentMethod === 0" /></template>
          </van-cell>
          <van-cell title="支付宝支付" @click="paymentMethod = 1">
            <template #icon><cp-icon name="consult-alipay" /></template>
            <template #extra><van-checkbox :checked="paymentMethod === 1" /></template>
          </van-cell>
        </van-cell-group>
        <div class="btn">
          <van-button @click="pay" type="primary" round block>立即支付</van-button>
        </div>
      </div>
    </van-action-sheet>
  </div>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}
.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
  .btn {
    padding: 15px;
  }
  .van-cell {
    align-items: center;
    .cp-icon {
      margin-right: 10px;
      font-size: 18px;
    }
    .van-checkbox :deep(.van-checkbox__icon) {
      font-size: 16px;
    }
  }
}
</style>
